<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="申请单号" prop="applyNo">
          <el-input v-model="queryParams.applyNo" placeholder="请输入申请单号" clearable size="small"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="申请类型" prop="applyType">
          <el-select v-model="queryParams.applyType" placeholder="请选择申请类型" clearable filterable size="small">
            <el-option v-for="dict in applyTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划单号" prop="planNo">
          <el-input v-model="queryParams.planNo" placeholder="请输入计划单号" clearable size="small"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="申请人" prop="applyUser">
          <el-select v-model="queryParams.applyUser" placeholder="请选择申请人" clearable filterable size="small">
            <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期">
          <el-date-picker v-model="daterangeApplyTime" size="small" style="width: 240px" value-format="YYYY-MM-DD"
            type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <el-select v-model="queryParams.applyStatus" placeholder="请选择申请状态" clearable filterable size="small">
            <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" prop="auditUser">
          <el-select v-model="queryParams.auditUser" placeholder="请选择审核人" clearable filterable size="small">
            <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核日期">
          <el-date-picker v-model="daterangeAuditTime" size="small" style="width: 240px" value-format="YYYY-MM-DD"
            type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable filterable size="small">
            <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="applyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="申请单号" align="center" prop="applyNo" width="150" />
        <el-table-column label="申请类型" align="center" prop="applyType" :formatter="applyTypeFormat" />
        <el-table-column label="计划单号" align="center" prop="planNo" width="150" />
        <el-table-column label="补货单号" align="center" prop="replenishNo"></el-table-column>
        <el-table-column label="申请人" align="center" prop="applyUser" :formatter="applyUserFormat" />
        <el-table-column label="申请日期" align="center" prop="applyTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请状态" align="center" prop="applyStatus" :formatter="applyStatusFormat" />
        <el-table-column label="审核人" align="center" prop="auditUser" :formatter="auditUserFormat" />
        <el-table-column label="审核日期" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="auditStatusFormat" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
  
      <!-- 添加或修改采购申请对话框 -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" :inline="true">
          <el-form-item label="单据单号" prop="applyNo">
            <el-input v-model="form.applyNo" placeholder="请输入单据单号" disabled />
          </el-form-item>
          <el-form-item label="计划单号" prop="planNo">
            <el-input v-model="form.planNo" disabled></el-input>
          </el-form-item>
          <el-form-item label="申请人" prop="applyUser">
            <el-select v-model="form.applyUser" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请日期" prop="applyTime">
            <el-date-picker clearable size="small" v-model="form.applyTime" type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss" placeholder="" disabled>
            </el-date-picker>
          </el-form-item>
          <el-form-item label="申请状态" prop="applyStatus">
            <el-select v-model="form.applyStatus" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核人" prop="auditUser">
            <el-select v-model="form.auditUser" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核日期" prop="auditTime">
            <el-date-picker clearable size="small" v-model="form.auditTime" type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss" placeholder="" disabled>
            </el-date-picker>
          </el-form-item>
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="form.auditStatus" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核意见" prop="auditComment">
            <el-input v-model="form.auditComment" type="textarea" placeholder="请输入审核意见" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="" disabled />
          </el-form-item>
          <el-divider content-position="center">采购申请明细信息</el-divider>
          <el-table :data="scmPurchaseApplyDetailList" :row-class-name="rowScmPurchaseApplyDetailIndex"
            ref="scmPurchaseApplyDetailRef">
            <el-table-column label="序号" align="center" prop="index" width="50" />
            <el-table-column label="物料" prop="materialName" width="200"></el-table-column>
            <el-table-column label="型号" prop="materialModel"></el-table-column>
            <el-table-column label="规格" prop="materialSpecification"></el-table-column>
            <el-table-column label="单位" prop="materialUnit"></el-table-column>
            <el-table-column label="单价" prop="price" width="150"></el-table-column>
            <el-table-column label="采购数量" prop="quantity" width="150"></el-table-column>
            <el-table-column label="需求数量" prop="requireQuantity" width="150"></el-table-column>
            <el-table-column label="需求日期" prop="requireDate" width="240"></el-table-column>
            <el-table-column label="备注" prop="detailRemark" width="150"></el-table-column>
          </el-table>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button v-if="form.applyStatus!='2'" type="primary" @click="submitForm('1')">通 过</el-button>
            <el-button v-if="form.applyStatus!='2'" type="warning" @click="submitForm('0')">驳 回</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue'
  import { Search, Refresh, Edit } from '@element-plus/icons-vue'
  import { listApply4Audit, getApply, auditApply, listApplyDetailByPlanId } from "@/api/purchase/apply"
  import { ElMessage } from 'element-plus'
  import { parseTime } from '@/utils/ruoyi'
  import { getDicts } from '@/api/system/dict/data'
  import { selectDictLabel } from '@/utils/ruoyi'
  
  // 遮罩层
  const loading = ref(true)
  // 选中数组
  const ids = ref([])
  // 子表选中数据
  const checkedScmPurchaseApplyDetail = ref([])
  // 非单个禁用
  const single = ref(true)
  // 非多个禁用
  const multiple = ref(true)
  // 显示搜索条件
  const showSearch = ref(true)
  // 总条数
  const total = ref(0)
  // 采购申请表格数据
  const applyList = ref([])
  // 采购申请明细表格数据
  const scmPurchaseApplyDetailList = ref([])
  // 弹出层标题
  const title = ref("")
  // 是否显示弹出层
  const open = ref(false)
  // 类型字典
  const applyTypeOptions = ref([])
  // 申请人字典
  const applyUserOptions = ref([])
  // 申请日期时间范围
  const daterangeApplyTime = ref([])
  // 申请状态字典
  const applyStatusOptions = ref([])
  // 审核人字典
  const auditUserOptions = ref([])
  // 审核日期时间范围
  const daterangeAuditTime = ref([])
  // 审核状态字典
  const auditStatusOptions = ref([])
  
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    applyNo: null,
    planId: null,
    applyType: null,
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
    orderByColumn: 'apply_time',
    isAsc: 'desc',
  })
  
  // 表单参数
  const form = reactive({
    id: null,
    applyNo: null,
    planId: null,
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
    auditComment: null,
    remark: null,
    scmPurchaseApplyDetailList: [],
  })
  
  // 表单校验
  const checkAuditComment = (rule, value, callback) => {
    if (form.auditStatus == '0') {
      if (!value) {
        callback(new Error('请输入审核意见'))
      }
    }
    callback()
  }
  
  const rules = {
    auditComment: [{
      validator: checkAuditComment,
      trigger: 'blur'
    }]
  }
  
  const formRef = ref(null)
  const queryFormRef = ref(null)
  const scmPurchaseApplyDetailRef = ref(null)
  
  // 监听采购申请明细列表变化
  watch(scmPurchaseApplyDetailList, (newVal) => {
    form.scmPurchaseApplyDetailList = newVal
  }, { deep: true, immediate: true })
  
  /** 查询采购申请列表 */
  const getList = async () => {
    loading.value = true
    queryParams.params = {}
    if (daterangeApplyTime.value?.length > 0) {
      queryParams.params["beginApplyTime"] = daterangeApplyTime.value[0]
      queryParams.params["endApplyTime"] = daterangeApplyTime.value[1]
    }
    if (daterangeAuditTime.value?.length > 0) {
      queryParams.params["beginAuditTime"] = daterangeAuditTime.value[0]
      queryParams.params["endAuditTime"] = daterangeAuditTime.value[1]
    }
    try {
      const response = await listApply4Audit(queryParams)
      applyList.value = response.rows
      total.value = response.total
    } finally {
      loading.value = false
    }
  }
  
  // 申请类别字典翻译
  const applyTypeFormat = (row) => {
    return selectDictLabel(applyTypeOptions.value, row.applyType)
  }
  
  // 申请人字典翻译
  const applyUserFormat = (row) => {
    return selectDictLabel(applyUserOptions.value, row.applyUser)
  }
  
  // 申请状态字典翻译
  const applyStatusFormat = (row) => {
    return selectDictLabel(applyStatusOptions.value, row.applyStatus)
  }
  
  // 审核人字典翻译
  const auditUserFormat = (row) => {
    return selectDictLabel(auditUserOptions.value, row.auditUser)
  }
  
  // 审核状态字典翻译
  const auditStatusFormat = (row) => {
    return selectDictLabel(auditStatusOptions.value, row.auditStatus)
  }
  
  // 取消按钮
  const cancel = () => {
    open.value = false
    reset()
  }
  
  // 表单重置
  const reset = () => {
    Object.assign(form, {
      id: null,
      applyNo: null,
      planId: null,
      applyUser: null,
      applyTime: null,
      applyStatus: null,
      auditUser: null,
      auditTime: null,
      auditStatus: null,
      auditComment: null,
      remark: null,
      scmPurchaseApplyDetailList: [],
    })
    scmPurchaseApplyDetailList.value = []
    formRef.value?.resetFields()
  }
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }
  
  /** 重置按钮操作 */
  const resetQuery = () => {
    daterangeApplyTime.value = []
    daterangeAuditTime.value = []
    queryFormRef.value?.resetFields()
    handleQuery()
  }
  
  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    multiple.value = !selection.length
  }
  
  /** 修改按钮操作 */
  const handleUpdate = async (row) => {
    reset()
    const id = row.id || ids.value
    try {
      const response = await getApply(id)
      Object.assign(form, response.data)
      scmPurchaseApplyDetailList.value = response.data.scmPurchaseApplyDetailList
      open.value = true
      title.value = "审核采购申请"
    } catch (error) {
      console.error('获取采购申请详情失败:', error)
    }
  }
  
  /** 审核按钮 */
  const submitForm = async (status) => {
    form.auditStatus = status
    if (!formRef.value) return
    
    try {
      await formRef.value.validate()
      await auditApply(form)
      ElMessage.success("审核成功")
      open.value = false
      getList()
    } catch (error) {
      console.error('审核失败:', error)
    }
  }
  
  /** 采购申请明细序号 */
  const rowScmPurchaseApplyDetailIndex = ({ row, rowIndex }) => {
    row.index = rowIndex + 1
  }
  
  // 初始化
  onMounted(async () => {
    try {
      const [userRes, applyStatusRes, auditStatusRes, applyTypeRes] = await Promise.all([
        getDicts("sys_user"),
        getDicts("apply_status"),
        getDicts("audit_status"),
        getDicts("purchase_apply_type")
      ])
      
      applyUserOptions.value = userRes.data
      applyStatusOptions.value = applyStatusRes.data
      auditUserOptions.value = userRes.data
      auditStatusOptions.value = auditStatusRes.data
      applyTypeOptions.value = applyTypeRes.data
      
      await getList()
    } catch (error) {
      console.error('初始化失败:', error)
    }
  })
  </script>